﻿using System;
using System.IO;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

namespace Common
{
    public static class CompressionHelpers
    {
        public static byte[] Uncompress(byte[] compressed)
        {
            MemoryStream ms = new MemoryStream(compressed);
            MemoryStream outPutStream = new MemoryStream();

            ZipInputStream zipInputStream = new ZipInputStream(ms);
            ZipEntry zipEntry = zipInputStream.GetNextEntry();

            StreamUtils.Copy(zipInputStream, outPutStream, new byte[4096]);

            byte[] UncompressedData = new byte[outPutStream.Length];
            outPutStream.Seek(0, SeekOrigin.Begin);
            outPutStream.Read(UncompressedData, 0, (int)outPutStream.Length);

            return UncompressedData;
        }

        public static int[] ConvertByteArrayToIntArray(byte[] uncompress)
        {
            int arrayLength = uncompress.Length;
            int resultLength = arrayLength / 4;
            int[] result = new int[resultLength];

            for (int i = 0; i < resultLength; i++)
            {
                result[i] = BitConverter.ToInt32(uncompress, i * 4);
            }

            return result;
        }

        public static byte[] Compress(byte[] raw, string name)
        {
            MemoryStream outputMemStream = new MemoryStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputMemStream);
            zipOutputStream.SetLevel(9);

            ZipEntry newEntry = new ZipEntry(name);
            newEntry.DateTime = DateTime.UtcNow;
            zipOutputStream.PutNextEntry(newEntry);

            StreamUtils.Copy(new MemoryStream(raw), zipOutputStream, new byte[4096]);
            zipOutputStream.CloseEntry();
            zipOutputStream.Close();

            return outputMemStream.GetBuffer();
        }

        public static byte[] BtyeArrayFromIntArray(int[] intArray)
        {
            int arrayLength = intArray.Length;
            byte[] result = new byte[arrayLength * 4];
            for (int i = 0; i < arrayLength; i++)
            {
                Array.Copy(BitConverter.GetBytes(intArray[i]), 0, result, i * 4, 4);
            }

            return result;
        }
    }
}